package controllers;

import java.io.IOException;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.EmailModel;
import models.GeoModel;

import data.EmailData;
import data.GeoData;

public class ReceiveMessageServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		EmailModel email = new EmailModel();
		
		String s = (String) request.getParameter("s");
		if (s == null) {
			s = "email";
		}
		
		GeoData geoData = new GeoData();
		ArrayList<GeoModel> geos = geoData.getCities();
		
		request.setAttribute("s", s);
		request.setAttribute("check", check);
		request.setAttribute("geos", geos);
		request.setAttribute("email", email);
		try {
			request.getRequestDispatcher("/pages/receive_message.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		EmailData emailData = new EmailData();
		EmailModel email = new EmailModel();
		TreeMap check = new TreeMap();
		
		String s = (String) request.getParameter("s");
		if (s == null) {
			s = "email";
		}
		
		GeoData geoData = new GeoData();
		ArrayList<GeoModel> geos = geoData.getCities();
		
		String strEmail = (String) request.getParameter("email");
		String city = (String) request.getParameter("city");
		
		if (city == null || city.isEmpty()) {
			check.put("city", "Bạn chưa chọn Tỉnh/Thành Phố");
			email.setCity("");
		} else {
			email.setCity(city);
		}
		
		if (strEmail != null) {
			Pattern p = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
			Matcher m = p.matcher(strEmail);
			if (!m.matches()) {
				check.put("email", "Địa chỉ email không hợp lệ.");
			}
			email.setEmail(strEmail);
		} else {
			check.put("email", "Thông tin email chưa đựoc nhập.");
			email.setEmail("");
		}
		
		if (check.size() == 0) {
			emailData.insert(email);
			request.setAttribute("success", "<b>Xin chúc mừng!</b> Email của bạn đã được cập nhật vào hệ thống của chúng tôi. ");
		}
		
		request.setAttribute("s", s);
		request.setAttribute("check", check);
		request.setAttribute("geos", geos);
		request.setAttribute("email", email);
		try {
			request.getRequestDispatcher("/pages/receive_message.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
}
